import { RTSPHandler } from './rtspHandler.js';
import { EventEmitter } from 'events';

export class StreamManager extends EventEmitter {
  constructor(mediasoupRouter, config) {
    super();
    this.router = mediasoupRouter;
    this.config = config;
    this.streams = new Map(); // roomId -> RTSPHandler
    this.maxStreams = 16; // 最大支持16路流
  }

  // 获取或创建房间的RTSP流
  async getOrCreateStream(roomId, rtspUrl) {
    // 确保roomId是字符串类型
    const normalizedRoomId = String(roomId);
    
    console.log(`Getting or creating stream for room: ${normalizedRoomId}, URL: ${rtspUrl}`);
    
    // 检查是否已存在该房间的流
    if (this.streams.has(normalizedRoomId)) {
      const existingHandler = this.streams.get(normalizedRoomId);
      
      // 如果URL相同且流正在运行，直接返回
      if (existingHandler.rtspUrl === rtspUrl && existingHandler.isStreamActive()) {
        console.log(`Stream already exists for room ${normalizedRoomId}`);
        return {
          success: true,
          videoProducerId: existingHandler.getProducers().video?.id,
          audioProducerId: existingHandler.getProducers().audio?.id,
          isNew: false
        };
      }
      
      // URL不同或流已停止，需要重新启动
      console.log(`Restarting stream for room ${normalizedRoomId} with new URL`);
      await this.stopStream(normalizedRoomId);
    }
    
    // 检查流数量限制
    if (this.streams.size >= this.maxStreams) {
      throw new Error(`Maximum number of streams (${this.maxStreams}) reached`);
    }
    
    // 创建新的RTSP处理器
    const rtspHandler = new RTSPHandler(this.router, this.config);
    rtspHandler.rtspUrl = rtspUrl;
    
    // 监听流事件
    rtspHandler.on('streamStarted', (data) => {
      console.log(`Stream started for room ${normalizedRoomId}:`, data);
      this.emit('streamStarted', { roomId: normalizedRoomId, ...data });
    });
    
    rtspHandler.on('streamStopped', () => {
      console.log(`Stream stopped for room ${normalizedRoomId}`);
      this.emit('streamStopped', { roomId: normalizedRoomId });
    });
    
    // 启动流
    try {
      const result = await rtspHandler.startStream(rtspUrl);
      console.log("// 启动流-------------result", normalizedRoomId);
      this.streams.set(normalizedRoomId, rtspHandler);
      
      console.log(`New stream created for room ${normalizedRoomId}, videoProducerId: ${result.videoProducerId}`);
      return {
        success: true,
        videoProducerId: result.videoProducerId,
        audioProducerId: result.audioProducerId,
        isNew: true
      };
    } catch (error) {
      console.error(`Failed to start stream for room ${normalizedRoomId}:`, error);
      throw error;
    }
  }

  // 停止指定房间的流
  async stopStream(roomId) {
    // 确保roomId是字符串类型
    const normalizedRoomId = String(roomId);
    
    console.log(`Stopping stream for room: ${normalizedRoomId}`);
    
    // 检查所有streams的key，看是否有匹配的roomId
    let matchedRoomId = null;
    for (const [key] of this.streams) {
      if (key === normalizedRoomId) {
        matchedRoomId = key;
        break;
      }
    }
    
    if (matchedRoomId === null) {
      console.log(`No matching room ID found for: ${normalizedRoomId}`);
      console.log(`Available room IDs:`, Array.from(this.streams.keys()));
      return false;
    }
    
    const rtspHandler = this.streams.get(matchedRoomId);
    if (rtspHandler) {
      try {
        await rtspHandler.stopStream();
        this.streams.delete(matchedRoomId);
        console.log(`Stream stopped and removed for room ${matchedRoomId}`);
        return true;
      } catch (error) {
        console.error(`Error stopping stream for room ${matchedRoomId}:`, error);
        throw error;
      }
    }
    
    console.log(`No active stream found for room ${normalizedRoomId}`);
    return false;
  }

  // 获取指定房间的流信息
  getStreamInfo(roomId) {
    const rtspHandler = this.streams.get(roomId);
    if (rtspHandler && rtspHandler.isStreamActive()) {
      const producers = rtspHandler.getProducers();
      return {
        active: true,
        rtspUrl: rtspHandler.rtspUrl,
        videoProducerId: producers.video?.id,
        audioProducerId: producers.audio?.id
      };
    }
    return { active: false };
  }

  // 获取所有活跃流的信息
  getAllStreamsInfo() {
    const streamsInfo = {};
    for (const [roomId, rtspHandler] of this.streams) {
      if (rtspHandler.isStreamActive()) {
        const producers = rtspHandler.getProducers();
        streamsInfo[roomId] = {
          active: true,
          rtspUrl: rtspHandler.rtspUrl,
          videoProducerId: producers.video?.id,
          audioProducerId: producers.audio?.id
        };
      }
    }
    return streamsInfo;
  }

  // 获取指定房间的Producer
  getProducer(roomId, producerId) {
    console.log(`尝试获取Producer - roomId: ${roomId}, producerId: ${producerId}`);
    console.log("this.streams", this.streams);
    // 确保roomId是字符串类型
    const normalizedRoomId = String(roomId);
    
    // 检查所有streams的key，看是否有匹配的roomId
    let matchedRoomId = null;
    for (const [key] of this.streams) {
      if (key === normalizedRoomId) {
        matchedRoomId = key;
        break;
      }
    }
    
    if (matchedRoomId === null) {
      console.log(`未找到完全匹配的房间ID: ${normalizedRoomId}`);
      console.log(`可用的房间ID:`, Array.from(this.streams.keys()));
      return null;
    }
    
    const rtspHandler = this.streams.get(matchedRoomId);
    if (!rtspHandler) {
      console.log(`未找到房间 ${matchedRoomId} 的流处理器`);
      return null;
    }
    
    const producers = rtspHandler.getProducers();
    console.log(`房间 ${matchedRoomId} 的producers:`, {
      video: producers.video?.id || null,
      audio: producers.audio?.id || null
    });
    
    if (producers.video?.id === producerId) {
      console.log(`找到视频Producer: ${producerId}`);
      return producers.video;
    }
    if (producers.audio?.id === producerId) {
      console.log(`找到音频Producer: ${producerId}`);
      return producers.audio;
    }
    
    console.log(`未找到Producer: ${producerId}`);
    return null;
  }

  // 停止所有流
  async stopAllStreams() {
    console.log('Stopping all streams...');
    const stopPromises = [];
    
    for (const [roomId, rtspHandler] of this.streams) {
      stopPromises.push(rtspHandler.stopStream().catch(error => {
        console.error(`Error stopping stream for room ${roomId}:`, error);
      }));
    }
    
    await Promise.all(stopPromises);
    this.streams.clear();
    console.log('All streams stopped');
  }

  // 获取统计信息
  getStats() {
    return {
      totalStreams: this.streams.size,
      maxStreams: this.maxStreams,
      activeStreams: Array.from(this.streams.keys()).filter(roomId => {
        const handler = this.streams.get(roomId);
        return handler && handler.isStreamActive();
      }),
      availableSlots: this.maxStreams - this.streams.size
    };
  }

  // 列出所有可用的producers（用于调试）
  listAllProducers() {
    const allProducers = {};
    for (const [roomId, rtspHandler] of this.streams) {
      const producers = rtspHandler.getProducers();
      allProducers[roomId] = {
        video: producers.video?.id || null,
        audio: producers.audio?.id || null
      };
    }
    return allProducers;
  }
}
